package com.liao.domain.strategy.service.rule.filter.impl;

import com.liao.domain.strategy.model.entity.RuleActionEntity;
import com.liao.domain.strategy.model.entity.RuleMatterEntity;
import com.liao.domain.strategy.model.valobj.RuleLogicCheckTypeVO;
import com.liao.domain.strategy.repository.IStrategyRepository;
import com.liao.domain.strategy.service.annotation.LogicStrategy;
import com.liao.domain.strategy.service.rule.filter.ILogicFilter;
import com.liao.domain.strategy.service.rule.filter.factory.DefaultLogicFactory;
import com.liao.types.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;

/**
 * @Author long
 * @Description 【抽奖前规则】白名单用户过滤规则
 * @Date 2024-08-03 22:22
 */
@Slf4j
@Component
@LogicStrategy(logicMode = DefaultLogicFactory.LogicModel.RULE_WHITELIST)
public class RuleWhiteListLogicFilter implements ILogicFilter<RuleActionEntity.RaffleBeforeEntity> {

    @Resource
    private IStrategyRepository strategyRepository;

    @Override
    public RuleActionEntity<RuleActionEntity.RaffleBeforeEntity> filter(RuleMatterEntity ruleMatterEntity) {
        log.info("规则过滤-白名单 userId:{} strategyId:{} ruleModel:{}", ruleMatterEntity.getUserId(), ruleMatterEntity.getStrategyId(), ruleMatterEntity.getRuleModel());

        //数据结构：奖品ID:用户ID1,用户ID2,用户ID3
        String ruleValue = strategyRepository.queryStrategyRuleValue(ruleMatterEntity.getStrategyId(), ruleMatterEntity.getRuleModel(), ruleMatterEntity.getAwardId());
        String[] ruleValueSplit = ruleValue.split(Constants.COLON);
        Long awardId = Long.parseLong(ruleValueSplit[0]);
        String[] userWhiteList = ruleValueSplit[1].split(Constants.SPLIT);
        if (Arrays.asList(userWhiteList).contains(ruleMatterEntity.getUserId())) {
            return RuleActionEntity.<RuleActionEntity.RaffleBeforeEntity>builder()
                    .ruleModel(DefaultLogicFactory.LogicModel.RULE_WHITELIST.getCode())
                    .code(RuleLogicCheckTypeVO.TAKE_OVER.getCode())
                    .info(RuleLogicCheckTypeVO.TAKE_OVER.getInfo())
                    .data(RuleActionEntity.RaffleBeforeEntity.builder()
                            .awardId(awardId)
                            .build())
                    .build();
        }
        return RuleActionEntity.<RuleActionEntity.RaffleBeforeEntity>builder()
                .code(RuleLogicCheckTypeVO.ALLOW.getCode())
                .info(RuleLogicCheckTypeVO.ALLOW.getInfo())
                .build();
    }
}
